/*************************************************************************  
 *   This file is part of UBBMPSREADER.
 *
 *   UBBMPSREADER is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   UBBMPSREADER is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with UBBMPSREADER.  If not, see <http://www.gnu.org/licenses/>. 
 *************************************************************************/

package cs.ubbcluj.ro.mps.states;

import java.io.IOException;
import java.util.regex.Pattern;

import cs.ubbcluj.ro.mps.data.interfaces.Mps;
import cs.ubbcluj.ro.mps.reader.MpsInputStream;
import cs.ubbcluj.ro.mps.states.interfaces.State;
import cs.ubbcluj.ro.mps.states.utils.CharConstants;

/**
 * Represents the NAME section of the mps file
 * 
 * @author avadas
 * @version 1.0
 */
public strictfp class NameState extends AbstractState {

    /** The name of the section */
    private static final String NAME = "NAME";

    /**
     * 
     * @param nextState
     *            next state
     * @param errorState
     *            error state
     */
    public NameState(final State nextState, final State errorState) {
	super(nextState, errorState);
    }

    /**
     * {@inheritDoc}
     * 
     * @throws IOException
     */
    @Override
    public State nextState(final MpsInputStream input, final Mps mps)
	    throws IOException {

	int in = input.read();
	int index = 0;
	while ((in != -1) && (index < NameState.NAME.length())) {
	    if (in != NameState.NAME.charAt(index)) {
		return this.errorState;
	    }
	    index++;
	    in = input.read();
	}

	while ((in != -1) && (index < 14)) {
	    if (in != 32) {
		return this.errorState;
	    }
	    index++;
	    in = input.read();
	}

	final StringBuffer nameBuffer = new StringBuffer();
	while ((in != -1) && (in != CharConstants.LF)
		&& (in != CharConstants.CR)) {
	    nameBuffer.append((char) in);
	    in = input.read();
	}
	if (in == CharConstants.CR) {
	    input.read();
	}

	if (containsOnlySpaces(nameBuffer.toString())) {
	    return this.errorState;
	}

	mps.setName(nameBuffer.toString());
	return this.nextState;
    }

    private boolean containsOnlySpaces(final String name) {
	return Pattern.matches("([A-Z] | [a-z] | [0-9])*", name);

    }
}
